var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
import { jsxs as _jsxs, jsx as _jsx, Fragment as _Fragment } from "react/jsx-runtime";
import React from "react";
import { copyRangeBySelectData, copyRangeValue, isRange, rangeNumberStatistics, rangeNumberStatisticsBySelectData, } from "./service/RangeService";
import { copyToClipboard, formatPrice } from "../../../tools/Tools";
import DevPopup from "../DevPopup/DevPopup";
export function RangeTapHoc(WrappedComponent) {
    // 泛型限定
    let RangTap = class RangTap extends WrappedComponent {
    };
    RangTap = __decorate([
        ContextMenu
    ], RangTap);
    return RangTap;
}
/**
 ctrl + shift 选择方式
 * @param WrappedComponent
 * @constructor
 */
export function MultipleTapHoc(WrappedComponent) {
    // 泛型限定
    let MultipleTap = class MultipleTap extends WrappedComponent {
        constructor(...props) {
            super(...props);
            this.onRowClickMethod = this.onRowClickMethod.bind(this);
        }
        parent = super.render();
        isOnRowBoxSelected = false;
        onRowClickMethod(e) {
            const selectKeys = e.component.getSelectedRowKeys().length;
            if (selectKeys > 0) {
                this.isOnRowBoxSelected = true;
            }
            else {
                this.isOnRowBoxSelected = false;
            }
        }
        componentWillUnmount() {
            console.log("卸载dataSource");
            this.dataSource.dispose();
        }
        // ContextMenu(e) {
        //   let superMenus = super.ContextMenu(e);
        //   const grid = this.gridRef.current.instance;
        //   if (this.isOnRowBoxSelected) {
        //     const superMenusData = superMenus.map((el) => {
        //       if (el.text && el.text === "导出xlsx") {
        //         el.items.push({
        //           text: "导出所选xlsx",
        //           onItemClick: (e) => {
        //             this.onDataExporting(grid, true);
        //           },
        //         });
        //       }
        //       return el;
        //     });
        //     return superMenusData;
        //   } else {
        //     return superMenus;
        //   }
        // }
        render() {
            // const klass = classNames("cpas-grid");
            const p_props = this.props ? this.props : this.parent.props;
            const selection = this.parent?.props?.selection
                ? this.parent.props.selection
                : {
                    mode: "multiple",
                    selectAllMode: "allPages",
                    // deferred: true,
                    showCheckBoxesMode: "onLongTap",
                };
            let props = {
                ...p_props,
                onRowClick: this.onRowClickMethod,
                selection,
            };
            return React.cloneElement(this.parent, { ...props });
        }
    };
    MultipleTap = __decorate([
        ContextMenu
    ], MultipleTap);
    return MultipleTap;
}
export function MultipleCheckBoxHoc(WrappedComponent) {
    // 泛型限定
    return class extends WrappedComponent {
        parent = super.render();
        render() {
            const p_props = this.props ? this.props : this.parent.props;
            let props = {
                ...p_props,
                selection: {
                    mode: "multiple",
                    selectAllMode: "page",
                    showCheckBoxesMode: "always",
                },
            };
            return React.cloneElement(this.parent, { ...props });
        }
    };
}
export function ContextMenu(WrappedComponent) {
    return class extends WrappedComponent {
        constructor(...props) {
            super(...props);
            this.addMenuItems = this.addMenuItems.bind(this);
            this.onCellClickMethod = this.onCellClickMethod.bind(this);
            this.onCellHoverChangedMethod = this.onCellHoverChangedMethod.bind(this);
            this.onKeyDownMethod = this.onKeyDownMethod.bind(this);
            this.documentMouseUp = this.documentMouseUp.bind(this);
            this.documentMouseDown = this.documentMouseDown.bind(this);
        }
        selectedRange = {}; //Single Range
        multipleRange = []; // Multiple Range
        isSelectRange = false;
        isSelectionStopped;
        isMouseDown = false;
        parent = super.render();
        rangeModel = "m";
        currentMultipleRangeIndex = 0;
        isCheckBoxSelected = false;
        DevPopupRef = React.createRef();
        statisticsVals = {
            sum: 0,
            count: 0,
            avg: 0,
        };
        foreachRange(selectedRange, func) {
            if (this.rangeModel === "m") {
                for (let i = 0; i < selectedRange.length; i++) {
                    const range = selectedRange[i];
                    this.resolveRange(range, func);
                }
            }
            else {
                this.resolveRange(selectedRange, func);
            }
        }
        resolveRange(selectedRange, func) {
            if (selectedRange.startRowIndex >= 0) {
                const minRowIndex = Math.min(selectedRange.startRowIndex, selectedRange.endRowIndex);
                const maxRowIndex = Math.max(selectedRange.startRowIndex, selectedRange.endRowIndex);
                const minColumnIndex = Math.min(selectedRange.startColumnIndex, selectedRange.endColumnIndex);
                const maxColumnIndex = Math.max(selectedRange.startColumnIndex, selectedRange.endColumnIndex);
                for (let rowIndex = minRowIndex; rowIndex <= maxRowIndex; rowIndex++) {
                    for (let columnIndex = minColumnIndex; columnIndex <= maxColumnIndex; columnIndex++) {
                        func(rowIndex, columnIndex);
                    }
                }
            }
        }
        showSelection(component, selectedRange) {
            const selectedEl = component.element().querySelectorAll(".cell-selected");
            for (let i = 0; i < selectedEl.length; i++) {
                const el = selectedEl[i];
                if (el) {
                    el.classList.remove("cell-selected");
                }
            }
            this.foreachRange(selectedRange, function (rowIndex, columnIndex) {
                const el = component.getCellElement(rowIndex, columnIndex);
                if (el) {
                    const hasClassGroupCell = el.className.indexOf("group") > -1;
                    const hasCommand = el.className.indexOf("command") > -1;
                    if (!hasClassGroupCell && !hasCommand) {
                        el.classList.add("cell-selected");
                    }
                }
            });
        }
        //type 2 表示右键
        cellClick(e, type) {
            console.log("点击事件");
            //避免和原生选中行模式的冲突
            if (e.component.getSelectedRowKeys().length > 0) {
                this.multipleRange = [];
                this.showSelection(e.component, this.multipleRange);
                return;
            }
            const isCtrl = e.event.ctrlKey;
            const isShift = e.event.shiftKey;
            const isMetaKey = e.event.metaKey;
            let columnIndex = e.columnIndex;
            if (type !== 2) {
                const isEditElement = e.cellElement.className.indexOf("dx-editor-cell") > -1;
                if (isEditElement) {
                    return;
                }
            }
            else {
                //如果是右键事件默认传递的columnIndex位置不正确，需要重新获取一次
                if (e.column) {
                    columnIndex = e.component.getVisibleColumnIndex(e.column.dataField);
                }
                else {
                    return;
                }
            }
            // this.getGridInstance().clearSelection();
            const range = {
                startRowIndex: e.rowIndex,
                endRowIndex: e.rowIndex,
                startColumnIndex: columnIndex,
                endColumnIndex: columnIndex,
            };
            this.selectedRange = range;
            if (isShift) {
                this.multipleRange[this.currentMultipleRangeIndex].endColumnIndex =
                    columnIndex;
                this.multipleRange[this.currentMultipleRangeIndex].endRowIndex =
                    e.rowIndex;
            }
            else if (isCtrl || isMetaKey) {
                this.currentMultipleRangeIndex = this.multipleRange.length;
                this.multipleRange.push(range);
            }
            else {
                this.multipleRange = [range];
                this.currentMultipleRangeIndex = 0;
            }
            console.log("multipleRange");
            console.log(this.multipleRange);
            this.isSelectionStopped = false;
            if (this.rangeModel === "m") {
                this.showSelection(e.component, this.multipleRange);
            }
            else {
                this.showSelection(e.component, range);
            }
        }
        onCellClickMethod(e) {
            if (super.onCellClickMethod)
                super.onCellClickMethod(e);
            if (this.props.onCellClick)
                this.props.onCellClick(e);
            const el = e.cellElement;
            if (el.className.indexOf("command") > -1) {
                if (this.rangeModel === "m") {
                    this.multipleRange = [];
                    this.currentMultipleRangeIndex = 0;
                    this.showSelection(e.component, this.multipleRange);
                }
                else {
                    this.selectedRange = {};
                    this.showSelection(e.component, this.selectedRange);
                }
            }
            const selectKeys = e.component.getSelectedRowKeys().length;
            if (selectKeys > 0) {
                this.isCheckBoxSelected = true;
            }
            else {
                this.isCheckBoxSelected = false;
            }
            this.cellClick(e, 0);
        }
        onCellHoverChangedMethod(e) {
            if (e.component.getSelectedRowKeys().length > 0) {
                return;
            }
            const isCtrl = e.event.ctrlKey;
            const isMetaKey = e.event.metaKey;
            // 划选的时候是否按住鼠标
            if (this.isMouseDown && e.rowIndex > -1) {
                if (e.cellElement) {
                    const el = e.cellElement;
                    const hasClassGroupCell = el.className.indexOf("group") > -1;
                    const hasCommand = el.className.indexOf("command") > -1;
                    if (hasClassGroupCell || hasCommand) {
                        return;
                    }
                }
                const columnIndex = e.component.getVisibleColumnIndex(e.column.dataField);
                // 是否直接滑动，不经过cellClick处理。需要重置 startIndex
                const selectRange = this.multipleRange[this.currentMultipleRangeIndex];
                if (this.isSelectionStopped) {
                    let newRange = {
                        startRowIndex: e.rowIndex,
                        startColumnIndex: columnIndex,
                        endRowIndex: e.rowIndex,
                        endColumnIndex: columnIndex,
                    };
                    this.isSelectionStopped = false;
                    if (this.rangeModel === "m") {
                        if (isCtrl || isMetaKey) {
                            this.currentMultipleRangeIndex = this.multipleRange.length;
                            this.multipleRange.push(newRange);
                        }
                        else {
                            if (!selectRange) {
                                this.multipleRange[this.currentMultipleRangeIndex] = newRange;
                            }
                        }
                        this.multipleRange[this.currentMultipleRangeIndex].startRowIndex =
                            e.rowIndex;
                        this.multipleRange[this.currentMultipleRangeIndex].startColumnIndex = columnIndex;
                    }
                    else {
                        this.selectedRange = {};
                    }
                }
                if (this.rangeModel === "m") {
                    this.multipleRange[this.currentMultipleRangeIndex].endRowIndex =
                        e.rowIndex;
                    this.multipleRange[this.currentMultipleRangeIndex].endColumnIndex =
                        columnIndex;
                    this.showSelection(e.component, this.multipleRange);
                }
                else {
                    if (this.selectedRange.startRowIndex === undefined) {
                        this.selectedRange.startRowIndex = e.rowIndex;
                    }
                    if (this.selectedRange.startColumnIndex === undefined) {
                        this.selectedRange.startColumnIndex = columnIndex;
                    }
                    this.selectedRange.endRowIndex = e.rowIndex;
                    this.selectedRange.endColumnIndex = columnIndex;
                    this.showSelection(e.component, this.selectedRange);
                }
            }
            else {
                //松开鼠标时标识，划选范围停止
                this.isSelectionStopped = true;
            }
        }
        onKeyDownMethod(e) {
            const { metaKey, ctrlKey, key } = e.event;
            if ((ctrlKey || metaKey) && (key === "c" || key === "C")) {
                copyRangeValue(this.getSelectCellRange(), 2);
            }
        }
        getSelectCellRange() {
            const grid = this.gridRef.current.instance;
            const vals = [];
            const coords = [];
            const range = this.rangeModel === "m" ? this.multipleRange : this.selectedRange;
            this.foreachRange(range, function (rowIndex, columnIndex) {
                const flag = coords.includes(rowIndex + "_" + columnIndex);
                if (!flag) {
                    coords.push(rowIndex + "_" + columnIndex);
                    const el = grid.getCellElement(rowIndex, columnIndex);
                    if (el) {
                        vals.push({
                            coord: rowIndex + "_" + columnIndex,
                            val: grid.cellValue(rowIndex, columnIndex),
                            dataType: grid.getVisibleColumns()[columnIndex].dataType,
                            dataField: grid.getVisibleColumns()[columnIndex].dataField,
                            GUID: grid.getKeyByRowIndex(rowIndex),
                        });
                    }
                }
            });
            return vals;
        }
        componentDidMount() {
            super.componentDidMount();
            document.addEventListener("mousedown", this.documentMouseDown);
            document.addEventListener("mouseup", this.documentMouseUp);
        }
        documentMouseDown(e) {
            if (e.buttons === 1) {
                this.isMouseDown = true;
            }
        }
        documentMouseUp(e) {
            this.isMouseDown = false;
            if (this.props.afterMouseRangeCells) {
                const data = this.getSelectCellRange();
                if (data.length > 1) {
                    this.props.afterMouseRangeCells(data);
                }
            }
        }
        componentWillUnmount() {
            console.log("卸载事件");
            document.removeEventListener("mousedown", this.documentMouseDown);
            document.removeEventListener("mouseup", this.documentMouseUp);
            console.log("卸载dataSource");
            this.dataSource.dispose();
        }
        ContextMenu(e) {
            const { column, row, columnIndex, rowIndex } = e;
            if (!column) {
                return;
            }
            if (this.rangeModel === "m") {
                for (let i = 0; i < this.multipleRange.length; i++) {
                    const range = this.multipleRange[i];
                    const flag = isRange(range, rowIndex, columnIndex);
                    if (flag) {
                        this.isSelectRange = true;
                        break;
                    }
                    this.isSelectRange = false;
                }
            }
            else {
                this.isSelectRange = isRange(this.selectedRange, rowIndex, columnIndex);
            }
            if (!this.isSelectRange && e.target !== "header") {
                this.cellClick(e, 2);
            }
            const { dataField, dataType } = column;
            const selectedRowsData = e.component.getSelectedRowsData();
            const visibleColumns = e.component.getVisibleColumns();
            const dataFields = [];
            for (let i = 0; i < visibleColumns.length; i++) {
                const column = visibleColumns[i];
                if (column.dataField) {
                    dataFields.push(column.dataField);
                }
            }
            const totalCount = this.getGridInstance().totalCount();
            const rangeVal = this.getSelectCellRange();
            let statistics;
            if (this.isCheckBoxSelected) {
                statistics = rangeNumberStatisticsBySelectData(selectedRowsData, dataFields);
            }
            else {
                statistics = rangeNumberStatistics(rangeVal);
            }
            this.statisticsVals = statistics;
            let superMenus = super.ContextMenu(e);
            const grid = this.gridRef.current.instance;
            const rangeMenu = [
                {
                    text: "选择",
                    items: [
                        {
                            text: "选中整行",
                            onItemClick: () => {
                                const visibleColumns = this.getGridInstance().getVisibleColumns();
                                if (this.rangeModel === "m") {
                                    const startRowI = this.parent.props?.selection?.mode === "multiple" ? 1 : 0;
                                    for (let i = 0; i < this.multipleRange.length; i++) {
                                        const range = this.multipleRange[i];
                                        range.startColumnIndex = startRowI;
                                        range.endColumnIndex = visibleColumns.length - 1;
                                        this.showSelection(e.component, this.multipleRange);
                                    }
                                }
                                else {
                                    this.selectedRange.startColumnIndex = 0;
                                    this.selectedRange.endColumnIndex = visibleColumns.length - 1;
                                    this.showSelection(e.component, this.selectedRange);
                                }
                            },
                        },
                        {
                            text: "选中整列",
                            onItemClick: () => {
                                const visibleRowCount = this.getGridInstance().getVisibleRows().length;
                                if (this.rangeModel === "m") {
                                    for (let i = 0; i < this.multipleRange.length; i++) {
                                        const range = this.multipleRange[i];
                                        range.startRowIndex = 0;
                                        range.endRowIndex = visibleRowCount - 1;
                                        this.showSelection(e.component, this.multipleRange);
                                    }
                                }
                                else {
                                    this.selectedRange.startRowIndex = 0;
                                    this.selectedRange.endRowIndex = visibleRowCount - 1;
                                    this.showSelection(e.component, this.selectedRange);
                                }
                            },
                        },
                        {
                            text: "全选",
                            onItemClick: () => {
                                const visibleRowCount = this.getGridInstance().getVisibleRows().length;
                                const visibleColumns = this.getGridInstance().getVisibleColumns();
                                if (this.rangeModel === "m") {
                                    this.multipleRange = [];
                                    const startRowI = this.parent.props?.selection?.mode === "multiple" ? 1 : 0;
                                    this.multipleRange.push({
                                        startRowIndex: 0,
                                        endRowIndex: visibleRowCount - 1,
                                        startColumnIndex: startRowI,
                                        endColumnIndex: visibleColumns.length - 1,
                                    });
                                    this.currentMultipleRangeIndex = 0;
                                    this.showSelection(e.component, this.multipleRange);
                                }
                                else {
                                    this.selectedRange.startRowIndex = 0;
                                    this.selectedRange.endRowIndex = visibleRowCount - 1;
                                    this.selectedRange.startColumnIndex = 0;
                                    this.selectedRange.endColumnIndex = visibleColumns.length - 1;
                                    this.showSelection(e.component, this.selectedRange);
                                }
                            },
                        },
                    ],
                },
            ];
            const defaultMenu = [
                {
                    text: "复制",
                    onItemClick: () => {
                        if (this.isCheckBoxSelected) {
                            copyRangeBySelectData(selectedRowsData, dataFields, 2);
                        }
                        else {
                            copyRangeValue(this.getSelectCellRange(), 2);
                        }
                    },
                },
                {
                    text: "高级复制",
                    items: [
                        {
                            text: "文本",
                            onItemClick: () => {
                                if (this.isCheckBoxSelected) {
                                    copyRangeBySelectData(selectedRowsData, dataFields, 1);
                                }
                                else {
                                    copyRangeValue(this.getSelectCellRange(), 1);
                                }
                            },
                        },
                        {
                            text: "数值",
                            onItemClick: () => {
                                if (this.isCheckBoxSelected) {
                                    copyRangeBySelectData(selectedRowsData, dataFields, 0);
                                }
                                else {
                                    copyRangeValue(this.getSelectCellRange(), 0);
                                }
                            },
                        },
                        {
                            text: "全部",
                            onItemClick: () => {
                                if (this.isCheckBoxSelected) {
                                    copyRangeBySelectData(selectedRowsData, dataFields, 2);
                                }
                                else {
                                    copyRangeValue(this.getSelectCellRange(), 2);
                                }
                            },
                        },
                    ],
                },
                //  731 临时隐藏
                // {
                //   text: "查找",
                //   onItemClick() {
                //     const gridEl = e.component.element();
                //     gridEl.querySelectorAll(".dx-header-filter")[columnIndex].click();
                //   },
                // },
                {
                    text: "统计",
                    items: [
                        {
                            text: `记录${totalCount}条`,
                        },
                        {
                            text: `合计${formatPrice(statistics.sum)}(点击复制)`,
                            onItemClick: () => {
                                copyToClipboard(statistics.sum);
                            },
                        },
                        {
                            text: "统计数据",
                            onItemClick: () => {
                                this.DevPopupRef.current.show({
                                    title: "统计",
                                    okCallback: () => {
                                        console.log("确定回调函数");
                                    },
                                });
                            },
                        },
                    ],
                },
                {
                    text: "列固定",
                    items: [
                        {
                            text: "向左",
                            onItemClick: () => {
                                this.getGridInstance().columnOption(dataField, {
                                    fixed: true,
                                    fixedPosition: "left",
                                });
                            },
                        },
                        {
                            text: "向右",
                            onItemClick: () => {
                                this.getGridInstance().columnOption(dataField, {
                                    fixed: true,
                                    fixedPosition: "right",
                                });
                            },
                        },
                        {
                            text: "取消固定",
                            onItemClick: () => {
                                this.getGridInstance().columnOption(dataField, {
                                    fixed: false,
                                    fixedPosition: "right",
                                });
                            },
                        },
                    ],
                },
                //  731 临时隐藏
                // {
                //   text: "显示方式",
                //   items: [
                //     {
                //       text: "文本列宽",
                //       onItemClick: () => {
                //         this.getGridInstance().option("columnAutoWidth", true);
                //       },
                //     },
                //     {
                //       text: "平均列宽",
                //       onItemClick: () => {
                //         this.getGridInstance().option("columnAutoWidth", false);
                //       },
                //     },
                //   ],
                // },
            ];
            if (this.isCheckBoxSelected) {
                const superMenusData = superMenus.map((el) => {
                    if (el.text && el.text === "导出Excel") {
                        el.items.push({
                            text: "导出所选Excel",
                            onItemClick: (e) => {
                                this.onDataExporting(grid, true);
                            },
                        });
                    }
                    return el;
                });
                return [...superMenusData, ...defaultMenu];
            }
            else {
                // return [...superMenus, ...rangeMenu, ...defaultMenu]; 731临时隐藏
                return [...superMenus, ...defaultMenu];
            }
        }
        addMenuItems(e) {
            const contentMenu = this.ContextMenu(e);
            if (e.target === "content") {
                // e.items can be undefined
                if (!e.items)
                    e.items = [];
                // Add a custom menu item
                e.items = contentMenu;
            }
        }
        render() {
            //  this.parent.props 是第一次组件初始化的时候， props 从父元素过来
            const p_props = this.props ? this.props : this.parent.props;
            let props = {
                ...p_props,
                onContextMenuPreparing: this.addMenuItems,
                onCellClick: this.onCellClickMethod,
                onCellHoverChanged: this.onCellHoverChangedMethod,
                onKeyDown: this.onKeyDownMethod,
            };
            return (_jsxs(_Fragment, { children: [React.cloneElement(this.parent, { ...props }), _jsx(DevPopup.Default, { ref: this.DevPopupRef, height: 250, children: (user) => {
                            return (_jsx("div", { style: {
                                    display: "flex",
                                    justifyContent: "center",
                                    alignItems: "center",
                                }, children: _jsxs("div", { children: [_jsxs("p", { children: ["\u5747\u503C: ", formatPrice(this.statisticsVals.avg)] }), _jsxs("p", { children: ["\u8BA1\u6570: ", this.statisticsVals.count] }), _jsxs("p", { children: ["\u5408\u8BA1: ", formatPrice(this.statisticsVals.sum)] })] }) }));
                        } })] }));
        }
    };
}
